import React, { useState, useEffect, useRef } from 'react';
import { llmApi, LLMModel, Conversation, ChatMessage } from '../../services/llmApi';
import { useAuthStore } from '../../stores/authStore';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import './ChatPage.css';

// 粒子背景组件
const ParticlesBackground: React.FC = () => {
  useEffect(() => {
    const container = document.getElementById('particles-container');
    if (!container) return;

    const createParticle = () => {
      const particle = document.createElement('div');
      particle.className = 'particle';
      
      // 随机位置
      const left = Math.random() * 100;
      const size = Math.random() * 3 + 1;
      const duration = Math.random() * 6 + 4; 
      const delay = Math.random() * 5;
      
      particle.style.left = `${left}%`;
      particle.style.width = `${size}px`;
      particle.style.height = `${size}px`;
      particle.style.animationDuration = `${duration}s`;
      particle.style.animationDelay = `${delay}s`;
      
      // 随机透明度
      const opacity = Math.random() * 0.3 + 0.1;
      particle.style.opacity = opacity.toString();
      
      container.appendChild(particle);
      
      // 粒子动画结束后移除
      setTimeout(() => {
        if (particle.parentNode) {
          particle.remove();
        }
      }, duration * 1000 + delay * 1000);
    };

    // 创建初始粒子
    for (let i = 0; i < 20; i++) {
      createParticle();
    }

    // 定期创建新粒子
    const interval = setInterval(createParticle, 500);

    return () => {
      clearInterval(interval);
    };
  }, []);

  return (
    <div 
      id="particles-container" 
      className="particles-container"
    />
  );
};

interface ChatPageProps {}

const ChatPage: React.FC<ChatPageProps> = () => {
  const { user } = useAuthStore();
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [models, setModels] = useState<LLMModel[]>([]);
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [selectedConversation, setSelectedConversation] = useState<Conversation | null>(null);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [currentMessage, setCurrentMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isStreaming, setIsStreaming] = useState(false);
  const [streamingMessage, setStreamingMessage] = useState('');
  const [showNewChatModal, setShowNewChatModal] = useState(false);
  const [newChatTitle, setNewChatTitle] = useState('');
  const [selectedModelId, setSelectedModelId] = useState<number | null>(null);
  const [showRenameModal, setShowRenameModal] = useState(false);
  const [currentConversationId, setCurrentConversationId] = useState<number | null>(null);
  const [newTitle, setNewTitle] = useState('');
  const [messageTemplates, setMessageTemplates] = useState([
    { id: 1, title: '总结内容', content: '请总结以下内容：' },
    { id: 2, title: '翻译文本', content: '请将以下文本翻译成中文：' },
    { id: 3, title: '解释概念', content: '请解释以下概念：' },
    { id: 4, title: '代码优化', content: '请优化以下代码：' }
  ]);
  const [showTemplates, setShowTemplates] = useState(false);
  const [quotedMessage, setQuotedMessage] = useState<ChatMessage | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [searchTerm, setSearchTerm] = useState('');

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages, streamingMessage]);

  // 加载模型和对话列表
  useEffect(() => {
    loadModels();
    loadConversations();
  }, []);

  const loadModels = async () => {
    try {
      const modelList = await llmApi.getModels();
      setModels(modelList);
    } catch (error) {
      console.error('加载模型失败:', error);
    }
  };

  const loadConversations = async () => {
    try {
      const conversationList = await llmApi.getConversations();
      setConversations(conversationList);
    } catch (error) {
      console.error('加载对话列表失败:', error);
    }
  };

  // 选择对话
  const selectConversation = async (conversation: Conversation) => {
    setSelectedConversation(conversation);
    try {
      const history = await llmApi.getConversationHistory(conversation.id);
      setMessages(history.messages);
    } catch (error) {
      console.error('加载对话历史失败:', error);
    }
  };

  // 创建新对话
  const createNewConversation = async () => {
    if (!newChatTitle.trim() || !selectedModelId) return;

    try {
      const newConversation = await llmApi.createConversation({
        title: newChatTitle,
        llm_model_id: selectedModelId
      });
      
      setConversations([newConversation, ...conversations]);
      setSelectedConversation(newConversation);
      setMessages([]);
      setShowNewChatModal(false);
      setNewChatTitle('');
      setSelectedModelId(null);
    } catch (error) {
      console.error('创建对话失败:', error);
    }
  };

  // 发送消息
  const sendMessage = async () => {
    if (!currentMessage.trim() || !selectedConversation || isLoading) return;

    const userMessage = currentMessage;
    setCurrentMessage('');
    setIsLoading(true);

    // 如果有引用的消息，将其包含在发送的消息中
    let finalMessage = userMessage;
    if (quotedMessage) {
      finalMessage = `引用 ${quotedMessage.role === 'user' ? '您' : selectedConversation?.llm_model_name} 的消息:\n> ${quotedMessage.content}\n\n${userMessage}`;
      setQuotedMessage(null); // 清除引用消息
    }

    // 添加用户消息到界面
    const newUserMessage: ChatMessage = {
      id: Date.now(),
      conversation_id: selectedConversation.id,
      role: 'user',
      content: finalMessage,
      created_at: new Date().toISOString()
    };
    setMessages(prev => [...prev, newUserMessage]);

    try {
      // 使用流式响应
      setIsStreaming(true);
      setStreamingMessage('');
      
      const stream = await llmApi.sendMessageStream({
        conversation_id: selectedConversation.id,
        message: finalMessage
      });

      if (stream) {
        const reader = stream.getReader();
        const decoder = new TextDecoder();
        let fullResponse = '';

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.slice(6));
                if (data.content) {
                  fullResponse += data.content;
                  setStreamingMessage(fullResponse);
                }
                if (data.is_complete) {
                  // 流式响应完成，添加助手消息
                  const assistantMessage: ChatMessage = {
                    id: Date.now() + 1,
                    conversation_id: selectedConversation.id,
                    role: 'assistant',
                    content: fullResponse,
                    created_at: new Date().toISOString()
                  };
                  setMessages(prev => [...prev, assistantMessage]);
                  setStreamingMessage('');
                  setIsStreaming(false);
                }
              } catch (e) {
                console.error('解析流数据失败:', e);
              }
            }
          }
        }
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      // 如果流式失败，尝试普通请求
      try {
        const response = await llmApi.sendMessage({
          conversation_id: selectedConversation.id,
          message: finalMessage
        });
        
        const assistantMessage: ChatMessage = {
          id: response.message_id,
          conversation_id: selectedConversation.id,
          role: 'assistant',
          content: response.message,
          created_at: new Date().toISOString()
        };
        setMessages(prev => [...prev, assistantMessage]);
      } catch (fallbackError) {
        console.error('普通请求也失败:', fallbackError);
      }
      setIsStreaming(false);
      setStreamingMessage('');
    } finally {
      setIsLoading(false);
    }
  };

  // 删除对话
  const deleteConversation = async (conversationId: number) => {
    if (!confirm('确定要删除这个对话吗？')) return;

    try {
      await llmApi.deleteConversation(conversationId);
      setConversations(conversations.filter(c => c.id !== conversationId));
      if (selectedConversation?.id === conversationId) {
        setSelectedConversation(null);
        setMessages([]);
      }
    } catch (error) {
      console.error('删除对话失败:', error);
    }
  };

  // 重命名对话
  const renameConversation = async () => {
    if (!newTitle.trim() || !currentConversationId) return;

    try {
      await llmApi.updateConversationTitle(currentConversationId, newTitle);
      
      setConversations(conversations.map(c => 
        c.id === currentConversationId ? {...c, title: newTitle} : c
      ));
      
      if (selectedConversation?.id === currentConversationId) {
        setSelectedConversation({...selectedConversation, title: newTitle});
      }
      
      setShowRenameModal(false);
      setNewTitle('');
      setCurrentConversationId(null);
    } catch (error) {
      console.error('重命名对话失败:', error);
    }
  };

  const filteredConversations = conversations.filter(conversation => {
    return conversation.title.toLowerCase().includes(searchTerm.toLowerCase());
  });

  return (
    <div className="chat-page" style={{ 
      display: 'flex', 
      height: 'calc(100vh - 100px)', 
      backgroundColor: theme.contentBackground,
      color: theme.textPrimary,
      borderRadius: '8px',
      overflow: 'hidden'
    }}>
      <ParticlesBackground />
      {/* 侧边栏 */}
      <div className="chat-sidebar" style={{
        width: '280px',
        backgroundColor: theme.siderBackground,
        borderRight: `1px solid ${theme.borderColor}`,
        display: 'flex',
        flexDirection: 'column'
      }}>
        <div className="sidebar-header" style={{
          padding: '16px',
          borderBottom: `1px solid ${theme.borderColor}`,
          background: mode === 'dark' ? 
            'linear-gradient(180deg, rgba(0,0,0,0.95) 0%, rgba(20,20,20,0.9) 100%)' : 
            'rgba(255, 255, 255, 0.85)',
          backdropFilter: mode === 'dark' ? 'blur(25px)' : 'blur(15px)',
          position: 'relative'
        }}>
          <h3 style={{ 
            margin: 0, 
            color: theme.textPrimary,
            fontSize: '18px',
            fontWeight: 600,
            backgroundImage: mode === 'dark' ? 
              'linear-gradient(135deg, #fff 0%, #61dca3 100%)' : 
              'linear-gradient(135deg, #000 0%, #1890ff 100%)',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            backgroundClip: 'text'
          }}>AI 对话</h3>
          <div style={{ 
            display: 'flex', 
            gap: '8px', 
            marginTop: '12px' 
          }}>
            <button 
              className="new-chat-btn"
              onClick={() => setShowNewChatModal(true)}
              style={{
                flex: 1,
                padding: '8px 16px',
                backgroundColor: theme.glowColor,
                color: mode === 'dark' ? '#000' : '#fff',
                border: 'none',
                borderRadius: '6px',
                cursor: 'pointer',
                fontSize: '14px',
                fontWeight: 500,
                boxShadow: mode === 'dark' ? 
                  '0 4px 15px rgba(97, 220, 163, 0.3)' : 
                  '0 4px 15px rgba(24, 144, 255, 0.3)',
                transition: 'all 0.3s ease',
                position: 'relative',
                overflow: 'hidden'
              }}
              onMouseEnter={(e) => {
                (e.target as HTMLButtonElement).style.transform = 'translateY(-2px)';
                (e.target as HTMLButtonElement).style.boxShadow = mode === 'dark' ? 
                  '0 6px 20px rgba(97, 220, 163, 0.4)' : 
                  '0 6px 20px rgba(24, 144, 255, 0.4)';
              }}
              onMouseLeave={(e) => {
                (e.target as HTMLButtonElement).style.transform = 'translateY(0)';
                (e.target as HTMLButtonElement).style.boxShadow = mode === 'dark' ? 
                  '0 4px 15px rgba(97, 220, 163, 0.3)' : 
                  '0 4px 15px rgba(24, 144, 255, 0.3)';
              }}
            >
              + 新对话
            </button>
            <button 
              className="clear-chat-btn"
              onClick={() => {
                if (selectedConversation) {
                  setMessages([]);
                }
              }}
              disabled={!selectedConversation}
              style={{
                padding: '8px 12px',
                backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                color: theme.textPrimary,
                border: `1px solid ${theme.borderColor}`,
                borderRadius: '6px',
                cursor: selectedConversation ? 'pointer' : 'not-allowed',
                fontSize: '14px',
                fontWeight: 500,
                transition: 'all 0.3s ease'
              }}
              onMouseEnter={(e) => {
                if (selectedConversation) {
                  (e.target as HTMLButtonElement).style.backgroundColor = mode === 'dark' ? 
                    'rgba(255, 255, 255, 0.15)' : 'rgba(0, 0, 0, 0.1)';
                }
              }}
              onMouseLeave={(e) => {
                if (selectedConversation) {
                  (e.target as HTMLButtonElement).style.backgroundColor = mode === 'dark' ? 
                    'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)';
                }
              }}
            >
              🗑️
            </button>
          </div>
        </div>
        
        {/* 对话搜索 */}
        <div style={{ padding: '8px' }}>
          <input
            type="text"
            placeholder="搜索对话..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            style={{
              width: '100%',
              padding: '8px 12px',
              borderRadius: '6px',
              border: `1px solid ${theme.borderColor}`,
              backgroundColor: theme.listBackground,
              color: theme.textPrimary,
              fontSize: '14px',
              transition: 'all 0.3s ease',
              backdropFilter: mode === 'dark' ? 'blur(10px)' : 'blur(5px)'
            }}
            onFocus={(e) => {
              (e.target as HTMLInputElement).style.boxShadow = `0 0 0 2px ${theme.glowColor}44`;
              (e.target as HTMLInputElement).style.transform = 'translateY(-1px)';
            }}
            onBlur={(e) => {
              (e.target as HTMLInputElement).style.boxShadow = 'none';
              (e.target as HTMLInputElement).style.transform = 'translateY(0)';
            }}
          />
        </div>
        
        <div className="conversation-list" style={{
          flex: 1,
          overflowY: 'auto',
          padding: '8px',
          backgroundColor: theme.listBackground,
          backdropFilter: mode === 'dark' ? 'blur(25px)' : 'blur(15px)'
        }}>
          {filteredConversations.map(conversation => (
            <div
              key={conversation.id}
              className={`conversation-item ${selectedConversation?.id === conversation.id ? 'active' : ''}`}
              onClick={() => selectConversation(conversation)}
              style={{
                padding: '16px',
                marginBottom: '12px',
                borderRadius: '12px',
                backgroundColor: theme.listBackground,
                border: `1px solid ${selectedConversation?.id === conversation.id ? 
                  theme.glowColor : theme.listBorder}`,
                cursor: 'pointer',
                transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                position: 'relative',
                backdropFilter: mode === 'dark' ? 'blur(10px)' : 'none',
                boxShadow: mode === 'dark' ? '0 2px 8px rgba(0, 0, 0, 0.2)' : '0 1px 3px rgba(0, 0, 0, 0.1)',
                // 添加选中状态的特殊样式
                ...(selectedConversation?.id === conversation.id && {
                  background: mode === 'dark' ? 
                    `linear-gradient(135deg, rgba(97, 220, 163, 0.2), rgba(78, 205, 196, 0.1))` : 
                    `linear-gradient(135deg, rgba(97, 220, 163, 0.25), rgba(78, 205, 196, 0.15))`,
                  border: `1px solid ${theme.glowColor}`,
                })
              }}
              onMouseEnter={(e) => {
                // 显示删除按钮和操作按钮
                const deleteBtn = (e.target as HTMLElement).querySelector('.delete-btn');
                const actions = (e.target as HTMLElement).querySelector('.conversation-actions');
                if (deleteBtn) (deleteBtn as HTMLElement).style.opacity = '1';
                if (actions) (actions as HTMLElement).style.opacity = '1';
                
                // 悬停效果
                if (mode === 'dark') {
                  (e.target as HTMLDivElement).style.background = selectedConversation?.id === conversation.id ? 
                    'rgba(97, 220, 163, 0.2)' : 'rgb(5, 5, 5)';
                  (e.target as HTMLDivElement).style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.3)';
                  (e.target as HTMLDivElement).style.transform = 'translateX(4px)';
                } else {
                  (e.target as HTMLDivElement).style.background = selectedConversation?.id === conversation.id ? 
                    'rgba(97, 220, 163, 0.25)' : 'rgb(5, 5, 5)';
                  (e.target as HTMLDivElement).style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
                  (e.target as HTMLDivElement).style.transform = 'translateX(4px)';
                }
              }}
              onMouseLeave={(e) => {
                // 隐藏删除按钮和操作按钮
                const deleteBtn = (e.target as HTMLElement).querySelector('.delete-btn');
                const actions = (e.target as HTMLElement).querySelector('.conversation-actions');
                if (deleteBtn) (deleteBtn as HTMLElement).style.opacity = '0';
                if (actions) (actions as HTMLElement).style.opacity = '0';
                
                // 恢复默认样式
                if (selectedConversation?.id === conversation.id) {
                  (e.target as HTMLDivElement).style.background = mode === 'dark' ? 
                    'rgba(97, 220, 163, 0.15)' : 'rgba(97, 220, 163, 0.2)';
                } else {
                  (e.target as HTMLDivElement).style.background = 'rgb(5, 5, 5)';
                }
                (e.target as HTMLDivElement).style.boxShadow = mode === 'dark' ? 
                  '0 2px 8px rgba(0, 0, 0, 0.2)' : '0 1px 3px rgba(0, 0, 0, 0.1)';
                (e.target as HTMLDivElement).style.transform = 'translateX(0)';
              }}
            >
              <div className="conversation-title" style={{
                color: theme.textPrimary,
                fontWeight: selectedConversation?.id === conversation.id ? 600 : 500,
                marginBottom: '4px',
                fontSize: '14px',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}>
                <span>{conversation.title}</span>
                <span style={{ 
                  fontSize: '10px', 
                  color: theme.textSecondary,
                  backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                  padding: '2px 6px',
                  borderRadius: '4px'
                }}>
                  {new Date(conversation.updated_at || conversation.created_at).toLocaleDateString()}
                </span>
              </div>
              <div className="conversation-meta" style={{
                display: 'flex',
                justifyContent: 'space-between',
                fontSize: '12px'
              }}>
                <span className="model-name" style={{ color: theme.textSecondary }}>
                  {conversation.llm_model_name}
                </span>
                <span className="message-count" style={{ color: theme.textSecondary }}>
                  {conversation.message_count} 条消息
                </span>
              </div>
              <button
                className="delete-btn"
                onClick={(e) => {
                  e.stopPropagation();
                  deleteConversation(conversation.id);
                }}
                style={{
                  position: 'absolute',
                  top: '8px',
                  right: '8px',
                  background: mode === 'dark' ? 'rgba(255, 107, 107, 0.2)' : 'rgba(255, 107, 107, 0.1)',
                  border: `1px solid ${mode === 'dark' ? 'rgba(255, 107, 107, 0.3)' : 'rgba(255, 107, 107, 0.2)'}`,
                  color: mode === 'dark' ? '#ff6b6b' : '#ff5252',
                  fontSize: '16px',
                  cursor: 'pointer',
                  opacity: 0,
                  transition: 'all 0.2s ease',
                  width: '20px',
                  height: '20px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  borderRadius: '50%'
                }}
              >
                ×
              </button>
              {/* 重命名和导出按钮 */}
              <div className="conversation-actions" style={{
                position: 'absolute',
                top: '8px',
                right: '32px',
                display: 'flex',
                gap: '4px',
                opacity: 0,
                transition: 'opacity 0.2s ease'
              }}>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    setCurrentConversationId(conversation.id);
                    setNewTitle(conversation.title);
                    setShowRenameModal(true);
                  }}
                  style={{
                    background: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                    border: `1px solid ${theme.borderColor}`,
                    color: theme.textPrimary,
                    width: '20px',
                    height: '20px',
                    borderRadius: '4px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: 'pointer',
                    fontSize: '10px'
                  }}
                  title="重命名对话"
                >
                  ✏️
                </button>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    // 导出对话功能
                    const conversationData = {
                      title: conversation.title,
                      model: conversation.llm_model_name,
                      messages: messages.filter(m => m.conversation_id === conversation.id),
                      createdAt: conversation.created_at,
                      updatedAt: conversation.updated_at
                    };
                    const dataStr = JSON.stringify(conversationData, null, 2);
                    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
                    const exportFileDefaultName = `${conversation.title}.json`;
                    const linkElement = document.createElement('a');
                    linkElement.setAttribute('href', dataUri);
                    linkElement.setAttribute('download', exportFileDefaultName);
                    linkElement.click();
                  }}
                  style={{
                    background: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                    border: `1px solid ${theme.borderColor}`,
                    color: theme.textPrimary,
                    width: '20px',
                    height: '20px',
                    borderRadius: '4px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: 'pointer',
                    fontSize: '10px'
                  }}
                  title="导出对话"
                >
                  📤
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 主聊天区域 */}
      <div className="chat-main" style={{
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        backgroundColor: theme.contentBackground
      }}>
        {selectedConversation ? (
          <>
            {/* 聊天头部 */}
            <div className="chat-header" style={{
              padding: '16px',
              borderBottom: `1px solid ${theme.borderColor}`,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center'
            }}>
              <h3 style={{ 
                margin: 0, 
                color: theme.textPrimary,
                fontSize: '18px'
              }}>{selectedConversation.title}</h3>
              <div className="model-info" style={{
                display: 'flex',
                gap: '8px'
              }}>
                <span className="provider" style={{ 
                  color: theme.textSecondary,
                  fontSize: '12px',
                  padding: '4px 8px',
                  backgroundColor: `${theme.glowColor}22`,
                  borderRadius: '4px'
                }}>{selectedConversation.provider}</span>
                <span className="model-name" style={{ 
                  color: theme.textSecondary,
                  fontSize: '12px',
                  padding: '4px 8px',
                  backgroundColor: `${theme.glowColor}22`,
                  borderRadius: '4px'
                }}>{selectedConversation.llm_model_name}</span>
              </div>
            </div>

            {/* 消息列表 */}
            <div className="messages-container" style={{
              flex: 1,
              overflowY: 'auto',
              padding: '16px',
              display: 'flex',
              flexDirection: 'column'
            }}>
              {messages.map(message => (
                <div key={message.id} className={`message ${message.role}`} style={{
                  marginBottom: '16px',
                  display: 'flex',
                  justifyContent: message.role === 'user' ? 'flex-end' : 'flex-start'
                }}>
                  {message.role === 'assistant' && (
                    <div style={{ 
                      width: '32px', 
                      height: '32px', 
                      borderRadius: '50%', 
                      backgroundColor: theme.glowColor,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      marginRight: '12px',
                      flexShrink: 0
                    }}>
                      <span style={{ 
                        color: mode === 'dark' ? '#000' : '#fff',
                        fontWeight: 'bold',
                        fontSize: '16px'
                      }}>🤖</span>
                    </div>
                  )}
                  <div className="message-content" style={{
                    maxWidth: '80%',
                    padding: '16px 20px',
                    borderRadius: '18px',
                    backgroundColor: theme.siderBackground,
                    color: theme.textPrimary,
                    boxShadow: mode === 'dark' ? 
                      '0 4px 12px rgba(0, 0, 0, 0.15)' : '0 4px 12px rgba(0, 0, 0, 0.08)',
                    position: 'relative',
                    border: `1px solid ${theme.borderColor}`,
                    transition: 'all 0.3s ease'
                  }}
                  onMouseEnter={(e) => {
                    const actions = (e.target as HTMLElement).querySelector('.message-actions');
                    if (actions) {
                      (actions as HTMLElement).style.opacity = '1';
                    }
                    // 添加悬停效果
                    (e.target as HTMLElement).style.transform = 'translateY(-2px)';
                    (e.target as HTMLElement).style.boxShadow = mode === 'dark' ? 
                      '0 6px 16px rgba(0, 0, 0, 0.2)' : '0 6px 16px rgba(0, 0, 0, 0.12)';
                  }}
                  onMouseLeave={(e) => {
                    const actions = (e.target as HTMLElement).querySelector('.message-actions');
                    if (actions) {
                      (actions as HTMLElement).style.opacity = '0';
                    }
                    // 恢复默认效果
                    (e.target as HTMLElement).style.transform = 'translateY(0)';
                    (e.target as HTMLElement).style.boxShadow = mode === 'dark' ? 
                      '0 4px 12px rgba(0, 0, 0, 0.15)' : '0 4px 12px rgba(0, 0, 0, 0.08)';
                  }}
                  >
                    <div className="message-text" style={{
                      lineHeight: '1.5',
                      whiteSpace: 'pre-wrap'
                    }}>{message.content}</div>
                    <div className="message-time" style={{
                      marginTop: '8px',
                      fontSize: '12px',
                      color: theme.textSecondary + '80',
                      textAlign: 'right',
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center'
                    }}>
                      <div>
                        {message.role === 'user' ? '您' : selectedConversation.llm_model_name}
                      </div>
                      <div>
                        {new Date(message.created_at).toLocaleString()}
                      </div>
                    </div>
                    {/* 消息操作按钮 */}
                    <div className="message-actions" style={{
                      position: 'absolute',
                      top: '8px',
                      right: '8px',
                      display: 'flex',
                      gap: '4px',
                      opacity: 0,
                      transition: 'opacity 0.2s ease'
                    }}>
                      <button
                        onClick={() => {
                          navigator.clipboard.writeText(message.content);
                          // 可以添加一个提示，表示已复制
                        }}
                        style={{
                          background: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                          border: `1px solid ${theme.borderColor}`,
                          color: theme.textPrimary,
                          width: '24px',
                          height: '24px',
                          borderRadius: '4px',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          cursor: 'pointer',
                          fontSize: '12px'
                        }}
                        title="复制消息"
                      >
                        📋
                      </button>
                      <button
                        onClick={() => {
                          setQuotedMessage(message);
                        }}
                        style={{
                          background: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                          border: `1px solid ${theme.borderColor}`,
                          color: theme.textPrimary,
                          width: '24px',
                          height: '24px',
                          borderRadius: '4px',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          cursor: 'pointer',
                          fontSize: '12px'
                        }}
                        title="引用消息"
                      >
                        ↪️
                      </button>
                      {message.role === 'user' && (
                        <button
                          onClick={() => {
                            if (confirm('确定要删除这条消息吗？')) {
                              setMessages(prev => prev.filter(m => m.id !== message.id));
                            }
                          }}
                          style={{
                            background: mode === 'dark' ? 'rgba(255, 107, 107, 0.2)' : 'rgba(255, 107, 107, 0.1)',
                            border: `1px solid ${mode === 'dark' ? 'rgba(255, 107, 107, 0.3)' : 'rgba(255, 107, 107, 0.2)'}`,
                            color: mode === 'dark' ? '#ff6b6b' : '#ff5252',
                            width: '24px',
                            height: '24px',
                            borderRadius: '4px',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            cursor: 'pointer',
                            fontSize: '12px'
                          }}
                          title="删除消息"
                        >
                          🗑️
                        </button>
                      )}
                    </div>
                  </div>
                  {message.role === 'user' && (
                    <div style={{ 
                      width: '32px', 
                      height: '32px', 
                      borderRadius: '50%', 
                      backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      marginLeft: '12px',
                      flexShrink: 0
                    }}>
                      <span style={{ 
                        color: theme.textPrimary,
                        fontWeight: 'bold',
                        fontSize: '16px'
                      }}>👤</span>
                    </div>
                  )}
                </div>
              ))}
              
              {/* 流式响应消息 */}
              {isStreaming && streamingMessage && (
                <div className="message assistant streaming" style={{
                  marginBottom: '16px',
                  display: 'flex',
                  justifyContent: 'flex-start'
                }}>
                  <div style={{ 
                    width: '32px', 
                    height: '32px', 
                    borderRadius: '50%', 
                    backgroundColor: theme.glowColor,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginRight: '12px',
                    flexShrink: 0
                  }}>
                    <span style={{ 
                      color: mode === 'dark' ? '#000' : '#fff',
                      fontWeight: 'bold',
                      fontSize: '16px'
                    }}>🤖</span>
                  </div>
                  <div className="message-content" style={{
                    maxWidth: '80%',
                    padding: '12px 16px',
                    borderRadius: '12px',
                    backgroundColor: theme.siderBackground,
                    color: theme.textPrimary,
                    boxShadow: mode === 'dark' ? 
                      '0 2px 4px rgba(0, 0, 0, 0.3)' : '0 2px 4px rgba(0, 0, 0, 0.1)',
                    position: 'relative'
                  }}>
                    <div className="message-text" style={{
                      lineHeight: '1.5',
                      whiteSpace: 'pre-wrap'
                    }}>{streamingMessage}</div>
                    <div className="typing-indicator" style={{
                      display: 'flex',
                      alignItems: 'center',
                      marginTop: '8px'
                    }}>
                      <span style={{
                        width: '8px',
                        height: '8px',
                        borderRadius: '50%',
                        backgroundColor: theme.textSecondary,
                        marginRight: '4px',
                        animation: 'typing 1.4s infinite ease-in-out'
                      }}></span>
                      <span style={{
                        width: '8px',
                        height: '8px',
                        borderRadius: '50%',
                        backgroundColor: theme.textSecondary,
                        marginRight: '4px',
                        animation: 'typing 1.4s infinite ease-in-out 0.2s'
                      }}></span>
                      <span style={{
                        width: '8px',
                        height: '8px',
                        borderRadius: '50%',
                        backgroundColor: theme.textSecondary,
                        animation: 'typing 1.4s infinite ease-in-out 0.4s'
                      }}></span>
                    </div>
                  </div>
                </div>
              )}
              
              <div ref={messagesEndRef} />
            </div>

            {/* 输入区域 */}
            <div className="chat-input-container" style={{
              padding: '16px',
              borderTop: `1px solid ${theme.borderColor}`
            }}>
              {/* 引用消息显示 */}
              {quotedMessage && (
                <div style={{
                  marginBottom: '12px',
                  padding: '12px',
                  backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                  borderRadius: '8px',
                  borderLeft: `4px solid ${theme.glowColor}`,
                  position: 'relative'
                }}>
                  <div style={{
                    fontSize: '12px',
                    color: theme.textSecondary,
                    marginBottom: '4px',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center'
                  }}>
                    <span>
                      {quotedMessage.role === 'user' ? '您' : selectedConversation?.llm_model_name}
                    </span>
                    <button
                      onClick={() => setQuotedMessage(null)}
                      style={{
                        background: 'transparent',
                        border: 'none',
                        color: theme.textSecondary,
                        cursor: 'pointer',
                        fontSize: '16px'
                      }}
                    >
                      ×
                    </button>
                  </div>
                  <div style={{
                    fontSize: '14px',
                    color: theme.textPrimary,
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis'
                  }}>
                    {quotedMessage.content}
                  </div>
                </div>
              )}
              
              {/* 模板选择区域 */}
              {showTemplates && (
                <div style={{
                  marginBottom: '12px',
                  display: 'flex',
                  flexWrap: 'wrap',
                  gap: '8px',
                  maxHeight: '120px',
                  overflowY: 'auto',
                  padding: '8px',
                  backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.03)',
                  borderRadius: '8px'
                }}>
                  {messageTemplates.map(template => (
                    <button
                      key={template.id}
                      onClick={() => {
                        setCurrentMessage(template.content);
                        setShowTemplates(false);
                      }}
                      style={{
                        padding: '6px 12px',
                        backgroundColor: theme.glowColor,
                        color: mode === 'dark' ? '#000' : '#fff',
                        border: 'none',
                        borderRadius: '6px',
                        cursor: 'pointer',
                        fontSize: '12px',
                        fontWeight: 500
                      }}
                    >
                      {template.title}
                    </button>
                  ))}
                  <button
                    onClick={() => setShowTemplates(false)}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                      color: theme.textPrimary,
                      border: `1px solid ${theme.borderColor}`,
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '12px'
                    }}
                  >
                    关闭
                  </button>
                </div>
              )}
              
              <div className="chat-input" style={{
                display: 'flex',
                gap: '12px'
              }}>
                <textarea
                  value={currentMessage}
                  onChange={(e) => setCurrentMessage(e.target.value)}
                  placeholder="输入您的消息... (Ctrl+Enter发送)"
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && e.ctrlKey) {
                      e.preventDefault();
                      sendMessage();
                    } else if (e.key === 'Enter' && !e.shiftKey) {
                      e.preventDefault();
                      sendMessage();
                    } else if (e.key === '/' && e.ctrlKey) {
                      // Ctrl+/ 快捷键打开模板
                      e.preventDefault();
                      setShowTemplates(true);
                    }
                  }}
                  disabled={isLoading}
                  style={{
                    flex: 1,
                    padding: '12px',
                    borderRadius: '8px',
                    border: `1px solid ${theme.borderColor}`,
                    backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.05)',
                    color: theme.textPrimary,
                    resize: 'none',
                    minHeight: '60px',
                    maxHeight: '120px'
                  }}
                />
                <div style={{ 
                  display: 'flex', 
                  flexDirection: 'column', 
                  gap: '8px' 
                }}>
                  {/* 模板按钮 */}
                  <button
                    onClick={() => setShowTemplates(!showTemplates)}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                      color: theme.textPrimary,
                      border: `1px solid ${theme.borderColor}`,
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '12px',
                      fontWeight: 500
                    }}
                    title="消息模板 (Ctrl+/)"
                  >
                    📋
                  </button>
                  
                  {/* 快捷操作按钮 */}
                  <button
                    onClick={() => {
                      const quickCommands = [
                        '/help - 显示帮助信息',
                        '/clear - 清空当前对话',
                        '/reset - 重置对话上下文',
                        '/save - 保存当前对话'
                      ];
                      alert('快捷命令:\n' + quickCommands.join('\n'));
                    }}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                      color: theme.textPrimary,
                      border: `1px solid ${theme.borderColor}`,
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '12px',
                      fontWeight: 500
                    }}
                    title="快捷命令"
                  >
                    ⚡
                  </button>
                  
                  <button
                    onClick={sendMessage}
                    disabled={!currentMessage.trim() || isLoading}
                    className="send-btn"
                    style={{
                      padding: '12px 24px',
                      backgroundColor: currentMessage.trim() && !isLoading ? 
                        theme.glowColor : `${theme.glowColor}80`,
                      color: mode === 'dark' ? '#000' : '#fff',
                      border: 'none',
                      borderRadius: '8px',
                      cursor: currentMessage.trim() && !isLoading ? 'pointer' : 'not-allowed',
                      fontWeight: 500,
                      transition: 'all 0.2s ease'
                    }}
                  >
                    {isLoading ? '发送中...' : '发送'}
                  </button>
                  <button
                    onClick={() => {
                      if (selectedConversation && confirm('确定要清空当前对话吗？')) {
                        setMessages([]);
                      }
                    }}
                    disabled={!selectedConversation || messages.length === 0}
                    style={{
                      padding: '8px 16px',
                      backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                      color: theme.textPrimary,
                      border: `1px solid ${theme.borderColor}`,
                      borderRadius: '8px',
                      cursor: selectedConversation && messages.length > 0 ? 'pointer' : 'not-allowed',
                      fontSize: '12px'
                    }}
                  >
                    清空
                  </button>
                </div>
              </div>
              <div style={{ 
                marginTop: '8px', 
                fontSize: '12px', 
                color: theme.textSecondary,
                textAlign: 'right'
              }}>
                Ctrl+Enter 发送消息 | Ctrl+/ 打开模板
              </div>
            </div>
          </>
        ) : (
          <div className="no-conversation" style={{
            flex: 1,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center',
            textAlign: 'center',
            padding: '24px',
            color: theme.textSecondary
          }}>
            <h3 style={{ 
              color: theme.textPrimary,
              marginBottom: '12px'
            }}>🚀 开启AI对话之旅</h3>
            <p style={{ 
              marginBottom: '24px',
              maxWidth: '400px'
            }}>选择一个已有的对话开始聊天，或者创建新的对话体验智能AI助手</p>
            <button 
              className="start-chat-btn"
              onClick={() => setShowNewChatModal(true)}
              style={{
                padding: '12px 24px',
                backgroundColor: theme.glowColor,
                color: mode === 'dark' ? '#000' : '#fff',
                border: 'none',
                borderRadius: '8px',
                cursor: 'pointer',
                fontWeight: 500,
                fontSize: '16px'
              }}
            >
              ✨ 创建新对话
            </button>
          </div>
        )}
      </div>

      {/* 新对话模态框 */}
      {showNewChatModal && (
        <div className="modal-overlay" onClick={() => setShowNewChatModal(false)} style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.6)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 1000
        }}>
          <div className="modal" onClick={(e) => e.stopPropagation()} style={{
            backgroundColor: theme.contentBackground,
            borderRadius: '12px',
            padding: '24px',
            minWidth: '400px',
            maxWidth: '500px',
            boxShadow: mode === 'dark' ? 
              '0 8px 32px rgba(0, 0, 0, 0.3)' : '0 8px 32px rgba(0, 0, 0, 0.1)'
          }}>
            <h3 style={{ 
              margin: '0 0 24px 0', 
              color: theme.textPrimary 
            }}>创建新对话</h3>
            <div className="form-group" style={{
              marginBottom: '20px'
            }}>
              <label style={{ 
                display: 'block', 
                marginBottom: '8px', 
                color: theme.textPrimary,
                fontWeight: 500
              }}>对话标题</label>
              <input
                type="text"
                value={newChatTitle}
                onChange={(e) => setNewChatTitle(e.target.value)}
                placeholder="输入对话标题"
                style={{
                  width: '100%',
                  padding: '12px',
                  borderRadius: '8px',
                  border: `1px solid ${theme.borderColor}`,
                  backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.05)',
                  color: theme.textPrimary
                }}
              />
            </div>
            <div className="form-group" style={{
              marginBottom: '24px'
            }}>
              <label style={{ 
                display: 'block', 
                marginBottom: '8px', 
                color: theme.textPrimary,
                fontWeight: 500
              }}>选择模型</label>
              <select
                value={selectedModelId || ''}
                onChange={(e) => setSelectedModelId(Number(e.target.value))}
                style={{
                  width: '100%',
                  padding: '12px',
                  borderRadius: '8px',
                  border: `1px solid ${theme.borderColor}`,
                  backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.05)',
                  color: theme.textPrimary
                }}
              >
                <option value="" style={{ 
                  backgroundColor: mode === 'dark' ? '#1a1a1a' : '#ffffff' 
                }}>
                  请选择模型
                </option>
                {models.map(model => (
                  <option 
                    key={model.id} 
                    value={model.id}
                    style={{ 
                      backgroundColor: mode === 'dark' ? '#1a1a1a' : '#ffffff' 
                    }}
                  >
                    {model.name} ({model.provider})
                  </option>
                ))}
              </select>
            </div>
            <div className="modal-actions" style={{
              display: 'flex',
              justifyContent: 'flex-end',
              gap: '12px'
            }}>
              <button 
                onClick={() => setShowNewChatModal(false)}
                style={{
                  padding: '10px 20px',
                  backgroundColor: 'transparent',
                  color: theme.textPrimary,
                  border: `1px solid ${theme.borderColor}`,
                  borderRadius: '6px',
                  cursor: 'pointer'
                }}
              >
                取消
              </button>
              <button 
                onClick={createNewConversation}
                disabled={!newChatTitle.trim() || !selectedModelId}
                style={{
                  padding: '10px 20px',
                  backgroundColor: !newChatTitle.trim() || !selectedModelId ? 
                    `${theme.glowColor}80` : theme.glowColor,
                  color: mode === 'dark' ? '#000' : '#fff',
                  border: 'none',
                  borderRadius: '6px',
                  cursor: !newChatTitle.trim() || !selectedModelId ? 'not-allowed' : 'pointer'
                }}
              >
                创建
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* 重命名对话模态框 */}
      {showRenameModal && (
        <div className="modal-overlay" onClick={() => setShowRenameModal(false)} style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.6)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 1000
        }}>
          <div className="modal" onClick={(e) => e.stopPropagation()} style={{
            backgroundColor: theme.contentBackground,
            borderRadius: '12px',
            padding: '24px',
            minWidth: '400px',
            maxWidth: '500px',
            boxShadow: mode === 'dark' ? 
              '0 8px 32px rgba(0, 0, 0, 0.3)' : '0 8px 32px rgba(0, 0, 0, 0.1)'
          }}>
            <h3 style={{ 
              margin: '0 0 24px 0', 
              color: theme.textPrimary 
            }}>重命名对话</h3>
            <div className="form-group" style={{
              marginBottom: '24px'
            }}>
              <label style={{ 
                display: 'block', 
                marginBottom: '8px', 
                color: theme.textPrimary,
                fontWeight: 500
              }}>对话标题</label>
              <input
                type="text"
                value={newTitle}
                onChange={(e) => setNewTitle(e.target.value)}
                placeholder="输入新的对话标题"
                style={{
                  width: '100%',
                  padding: '12px',
                  borderRadius: '8px',
                  border: `1px solid ${theme.borderColor}`,
                  backgroundColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.05)',
                  color: theme.textPrimary
                }}
              />
            </div>
            <div className="modal-actions" style={{
              display: 'flex',
              justifyContent: 'flex-end',
              gap: '12px'
            }}>
              <button 
                onClick={() => setShowRenameModal(false)}
                style={{
                  padding: '10px 20px',
                  backgroundColor: 'transparent',
                  color: theme.textPrimary,
                  border: `1px solid ${theme.borderColor}`,
                  borderRadius: '6px',
                  cursor: 'pointer'
                }}
              >
                取消
              </button>
              <button 
                onClick={renameConversation}
                disabled={!newTitle.trim()}
                style={{
                  padding: '10px 20px',
                  backgroundColor: !newTitle.trim() ? 
                    `${theme.glowColor}80` : theme.glowColor,
                  color: mode === 'dark' ? '#000' : '#fff',
                  border: 'none',
                  borderRadius: '6px',
                  cursor: !newTitle.trim() ? 'not-allowed' : 'pointer'
                }}
              >
                确认
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* 添加打字动画样式 */}
      <style>{`
        @keyframes typing {
          0%, 60%, 100% { transform: translateY(0); }
          30% { transform: translateY(-5px); }
        }
      `}</style>
    </div>
  );
};

export default ChatPage;